package com.usoft;

import scala.concurrent.Future;
import akka.dispatch.Futures;
import akka.actor.ActorSystem;
import akka.dispatch.OnSuccess;

import java.util.concurrent.Callable;


/**
 * Created by liyanxin on 2015/1/8.
 */
public class HelloFuture2 {

    public final static class PrintResult<T> extends OnSuccess<T> {
        @Override
        public final void onSuccess(T t) {
            System.out.println(t);
        }
    }

    public static void main(String args[]) {
        ActorSystem system = ActorSystem.create("mySystem");

        /**
         * Future表示一个异步的任务，这个异步任务的执行由system.dispatcher()得到的ExecutionContextExecutor执行
         * Futures.future
         * Starts an asynchronous computation and returns a `Future` object with the result of that computation.
         *
         * The result becomes available once the asynchronous computation is completed.
         *
         * @param body     the asychronous computation
         * @param executor the execution context on which the future is run
         * @return the `Future` holding the result of the computation
         */
        Future<String> f = Futures.future(new Callable<String>() {
            public String call() throws InterruptedException {
                Thread.sleep(5000);
                return "Hello" + "World";
            }
        }, system.dispatcher());

        // system.dispatcher()返回一个ExecutionContextExecutor
        // 当异步任务执行成功时，打印执行结果
        f.onSuccess(new PrintResult<String>(), system.dispatcher());

        /**
         * This will stop the guardian actor, which in turn
         * will recursively stop all its child actors, then the system guardian
         * and the execute all registered termination handlers .
         */
        system.shutdown();
        System.out.println("system shutdown");
        System.out.println(system.dispatcher().hashCode());
    }
}
